<template>
  <div class="app-container">
    <div class="head-container">
      <el-card shadow="never">
        <div class="search-bar">
          <!-- 搜索 -->
          <el-form
            :inline="true"
            :model="searchModel"
            size="mini"
            class="demo-form-inline"
          >
            <el-form-item label="手机号">
              <el-input
                v-model="searchModel.mobile"
                placeholder="请输入手机号"
              ></el-input>
            </el-form-item>

            <el-form-item class="operations">
              <el-button
                type="primary"
                @click="search"
              >查询</el-button>
              <el-button
                type="default"
                @click="reset"
              >重置</el-button>
              <el-button
                v-if="checkPermission(['ADMIN', 'admin-user::add'])"
                type="danger"
                @click="createAdminUser"
              >创建管理员用户</el-button>
            </el-form-item>
          </el-form>
        </div>
      </el-card>
    </div>

    <el-card shadow="never">
      <div class="data-list-wrap">

        <el-table
          v-loading="loading"
          :data="list"
          size="small"
          style="width: 100%;"
        >
          <el-table-column
            prop="username"
            label="用户名"
          >
          </el-table-column>
          <el-table-column
            prop="mobile"
            label="手机号"
          >
          </el-table-column>
          <el-table-column label="角色">
            <template slot-scope="scope">
              <div v-if="scope.row.roles && scope.row.roles.length">
                {{ scope.row.roles.join(",") }}
              </div>
              <div v-else>
                未分配角色
              </div>
            </template>
          </el-table-column>
          <el-table-column label="状态">
            <template slot-scope="scope">
              {{ scope.row.enabled ? "正常" : "冻结"}}
            </template>

          </el-table-column>
          <el-table-column label="操作">
            <template slot-scope="scope">
              <div>
                <el-button
                  type="text"
                  v-if="checkPermission(['ADMIN', 'role:save-roles'])"
                  @click="configRole(scope.row)"
                >分配角色</el-button>
              </div>

              <div>
                <el-popover 
                        placement="top"
                        width="200"
                        :ref="'removeRole' + scope.row.id"
                        trigger="click"
                      >
                        <p>确定删除用户  "{{scope.row.username}}"  吗？</p>
                        <div style="text-align: right; margin: 0">
                          <el-button
                            size="mini"
                            type="text"
                            @click="
                              $refs['removeRole' + scope.row.id].doClose()
                            "
                            >取消</el-button
                          >
                          <el-button
                          :loading="opLoading"
                            type="primary"
                            size="mini"
                            @click="doRemoveRole(scope.row.id)"
                            >确定</el-button
                          >
                        </div>
                          <el-button
                  
                      v-permission="['ADMIN','admin-user::remove-role']"
                        type="text"
                      slot="reference"
                      :value="scope.row.id"
                    >
                      删除用户
                    </el-button>
                      </el-popover>
              </div>

              <div>
            
                <el-popover placement="top" width="200" :ref="'resetPasswrod' + scope.row.id" trigger="click">
                      <p>确定重置该用户密码吗？</p>
                      <div style="text-align: right; margin: 0">
                        <el-button size="mini" type="text" @click="
                          $refs['resetPasswrod' + scope.row.id].doClose()
                          ">取消</el-button>
                        <el-button :loading="opLoading" type="primary" size="mini"
                          @click="doResettingPassword(scope.row.id)">确定</el-button>
                      </div>
                      <el-button v-permission="['ADMIN','admin-user::resetting-password']"  type="text"
                        slot="reference" :value="scope.row.id">
                        重置密码
                      </el-button>
                    </el-popover>
              </div>

            </template>
          </el-table-column>
        </el-table>
      </div>
      <div class="paging-wrap">
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="searchModel.pageNo"
          :page-sizes="[10, 20, 50, 100]"
          :page-size="searchModel.pagesize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="searchModel.count"
        >
        </el-pagination>
      </div>
    </el-card>

    <el-dialog
      :close-on-click-modal="false"
      :modal-append-to-body="false"
      title="分配角色"
      class="dialog-action"
      width="30%"
      :visible.sync="configRoleDialog"
    >
      <el-form
        :model="configRoleForm"
        ref="configRoleForm"
        :rules="rules"
        size="mini"
      >
        <el-form-item label="用户名：">
          {{ configRoleForm.username }}
        </el-form-item>
        <el-form-item label="角色：">
          <el-select
            v-model="configRoleForm.roleIds"
            multiple
            placeholder="请选择"
          >
            <el-option
              v-for="item in options"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            >
            </el-option>
          </el-select>
        </el-form-item>

      </el-form>
      <div
        slot="footer"
        class="dialog-footer"
      >
        <el-button @click="configRoleDialog = false">取 消</el-button>
        <el-button
          type="primary"
          :loading="opLoading"
          @click="doConfigRole"
        >确 定</el-button>
      </div>
    </el-dialog>

    <el-dialog
      :modal-append-to-body="false"
      :close-on-click-modal="false" 
      title="创建管理员用户"
      class="dialog-action"
      width="30%"
      :visible.sync="createAdminUserDialog"
    >
      <el-form
        :model="form"
        ref="form"
        :rules="rules"
        size="mini"
      >
        <el-form-item
          label="用户名："
          prop="username"
        >
          <el-input
            v-model="form.username"
            placeholder="请输入用户名"
          ></el-input>
        </el-form-item>
        <el-form-item
          label="手机号："
          prop="mobile"
        >
          <el-input
            v-model="form.mobile"
            placeholder="请输入手机号"
          ></el-input>
        </el-form-item>
      </el-form>
      <div
        v-if="psw"
        style="color:red;margin-top:8px;"
      >用户创建成功，初始密码：{{ psw }}</div>
      <div
        slot="footer"
        class="dialog-footer"
      >
        <el-button @click="createAdminUserDialog = false">取 消</el-button>
        <el-button
          type="primary"
          :loading="opLoading"
          @click="doCreateAdminUser"
        >确 定</el-button>
      </div>
    </el-dialog>
    <!-- 重置密码 -->
      <el-dialog title="新密码" :close-on-click-modal="false" :modal-append-to-body="false" class="dialog-action"
          width="50%" :visible.sync="resettingPasswordDialog">
          <el-form :model="resettingForm" label-width="100px" >
            <el-form-item label="新密码:">
              <span class="text-danger">{{ resettingForm.password }}</span>
            </el-form-item>

          </el-form>
          <div slot="footer" class="dialog-footer">
            <el-button :loading="opLoading" type="primary" @click="doCopy($event)">复制</el-button>
          </div>
        </el-dialog>


  </div>
</template>


<script>
import {
  searchAdminUser,
  createAdminUser,
  listRole,
  romoveAdminUser,
  saveAdminUserRoles,
  resettingPassword
} from "@/api/business";
import clipboard from "../../utils/clipboard";
import checkPermission from "@/utils/permission";
const defaultModel = {
  mobile: null,
  username: null,
  pageNo: 1,
  pageSize: 10,
  count: 0,
};
export default {
  data() {
    return {
      options: [],
      configRoleDialog: false,
      configRoleForm: {},
      //角色列表
      roles: [],
      form: {},
      createAdminUserDialog: false,
      resettingPasswordDialog: false,
      list: [],
      loading: false,
      opLoading: false,
      searchModel: _.cloneDeep(defaultModel),
      psw: null,
      resettingForm:{
        password:"",
      },
     
      rules: {
        username: [
          { required: true, message: "请输入用户名", trigger: "blur" },
        ],
        mobile: [{ required: true, message: "请输入手机号", trigger: "blur" }],
      },
    };
  },
  components: {},
  methods: {
    checkPermission,



    configRole(row) {
      this.configRoleDialog = true;
      this.configRoleForm = _.cloneDeep(row);
    },

    doConfigRole() {
      this.opLoading = true;
      let form = {
        adminUserId: this.configRoleForm.id,
        roleIds: this.configRoleForm.roleIds,
      };
      saveAdminUserRoles(form).then((data) => {
        if (data.success) {
          this.$notify({
            title: "操作成功",
            type: "success",
            duration: 2500,
          });
          this.configRoleDialog = false;
          this.search();
        }
        this.opLoading = false;
      });
    },
    // 确认删除角色
    doRemoveRole(id){
      this.opLoading = true;
      romoveAdminUser(id).then((resp =>{
        if(resp.success){
          this.$notify({
              title: "删除成功",
              type: "success",
              duration: 2500,
          });
          this.$refs["removeRole" + id].doClose();
          this.search();
        }else{
          this.$message.error(resp.resultMessage);
        }
        this.opLoading = false;
      })).catch(err=>{

        })
    },

     // 确认重置密码
     doResettingPassword(id){
      this.opLoading = true;
      resettingPassword(id).then((resp =>{
        if(resp.success){
          this.$notify({
                title: "重置成功",
                type: "success",
                duration: 2500,
              });
          this.resettingForm.password = resp.data
          this.resettingPasswordDialog = true;
          this.$refs["resetPasswrod" + id].doClose();
          this.search();
        }else{
          this.$message.error(resp.resultMessage);
        }
        this.opLoading = false;
      })).catch(err=>{

        })
    },

      //复制链接
      doCopy(e) {
      let password = "新密码：" + this.resettingForm.password
      let info =  password
      clipboard(info, e);
    },

    createAdminUser() {
      this.createAdminUserDialog = true;
    },

    doCreateAdminUser() {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          this.opLoading = true;
          createAdminUser(this.form)
            .then((data) => {
              if (data.success) {
                this.$notify({
                  title: "创建成功",
                  type: "success",
                  duration: 2500,
                });
                this.psw = data.data;
                this.search();
              }
              this.opLoading = false;
            })
            .catch((err) => {
              console.log(err);
              this.opLoading = false;
            });
        } else {
          return false;
        }
      });
    },

    search() {
      this.getList(1);
    },

    getList(pageNo) {
      this.loading = true;
      if (pageNo != undefined) {
        this.searchModel.pageNo = pageNo;
      }

      let searchModel = _.cloneDeep(this.searchModel);
      searchAdminUser(this.compileSearchModel(searchModel))
        .then((data) => {
          this.searchModel.pageNo = ++data.pageNo;
          this.searchModel.count = data.count;
          this.searchModel.pageSize = data.pageSize;
          this.list = data.data;
          this.loading = false;
        })
        .catch((err) => {
          console.log(err.response.data.message);
        });
    },

    reset() {
      this.searchModel = _.cloneDeep(defaultModel);
      this.getList(1);
    },

    compileSearchModel(searchModel) {
      searchModel.pageNo = searchModel.pageNo - 1;

      return searchModel;
    },
    //修改分页
    handleSizeChange(val) {
      this.searchModel.pageSize = val;
      this.getList(1);
    },
    //修改页面
    handleCurrentChange(val) {
      this.getList(val);
    },
    init() {
      this.options = [];
      listRole().then((data) => {
        if (data.success) {
          let roles = data.data;
          for (let data of roles) {
            this.options.push({
              value: data.id,
              label: data.name,
            });
          }
        }
      });
      this.getList(1);
    },
  },
  mounted() {
    this.init();
  },
};
</script>

<style lang="scss" scoped>
</style>
